package com.geeaks.generator.util;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class VelocityUtils {
	
	public static <T> String getTemplate(String vmName, Map<String, Object> map) {
		VelocityEngine velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		Properties prop = new Properties();
		// 设置velocity的编码
		prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		velocityEngine.init(prop);
		Template template = velocityEngine.getTemplate(vmName);
		VelocityContext velocityContext = new VelocityContext();
		for (String key : map.keySet()) {
			velocityContext.put(key, map.get(key));
		}
		StringWriter sw = new StringWriter();
		template.merge(velocityContext, sw);
		return sw.toString();
	}
	
}
